﻿//========================================================= 
/**@file CommandRunner.h
 * @brief 命令配置执行器(组合多个子命令集合)
 * 
 * @date 2016-10-04   10:36:06
 * @author Zhyioo 
 * @version 1.0
 */ 
//--------------------------------------------------------- 
#ifndef _LIBZHOUYB_COMMANDRUNNER_H_
#define _LIBZHOUYB_COMMANDRUNNER_H_
//--------------------------------------------------------- 
#include "CommandDriver.h"
#include "CommonCmdDriver.h"
//--------------------------------------------------------- 
namespace zhou_yb {
namespace application {
namespace driver {
//--------------------------------------------------------- 
/// 命令集合设置器
class CommandSetter : public IEnumerator<ReadOnlyEnumerator<Ref<ComplexCommand> > >
{
public:
    typedef ReadOnlyEnumerator<Ref<ComplexCommand> > EnumeratorType;
protected:
    Ref<CommandCollection> _refCollection;
    list_t<Ref<ComplexCommand> > _cmd_pool;
    /// 命令名称匹配算法
    bool _Compare(const ByteArray& src, const ByteArray& cmd) const
    {
        if(!StringConvert::EndWith(src, cmd, true))
            return false;

        bool bCompare = true;
        if(src.GetLength() > cmd.GetLength())
        {
            size_t index = src.GetLength() - cmd.GetLength() - 1;
            bCompare = (src[index] == '.');
        }
        return bCompare;
    }
    /// 查找指定命令
    Ref<ComplexCommand> _LookUp(const char* name, const list_t<Ref<ComplexCommand> >& cmdlist) const
    {
        ByteArray cmdName(name);
        if(cmdlist.size() < 1 || cmdName.IsEmpty())
            return Ref<ComplexCommand>();

        list_t<Ref<ComplexCommand> >::const_iterator itr;
        Ref<ComplexCommand> lookUpCmd;
        size_t cmdLv = 0;
        size_t lvCount = 0;
        for(itr = cmdlist.begin();itr != cmdlist.end(); ++itr)
        {
            ByteArray srcName((*itr)->Name());
            // 后半部分匹配,并且前面的一个字符为 . 分隔符
            if(_Compare(srcName, cmdName))
            {
                // 检测命令层级
                size_t dotCount = StringConvert::GetSplitFlagCount(srcName, '.');
                // 已经是顶层的命令
                if(dotCount < 1)
                    return (*itr);
                if(lookUpCmd.IsNull())
                {
                    lookUpCmd = (*itr);
                    cmdLv = dotCount;
                    continue;
                }
                if(cmdLv == dotCount)
                    ++lvCount;

                if(cmdLv > dotCount)
                {
                    cmdLv = dotCount;
                    lookUpCmd = (*itr);

                    lvCount = 0;
                }
            }
        }
        if(lvCount > 0)
            return Ref<ComplexCommand>();

        return lookUpCmd;
    }
    /// 提取一组命令
    CommandSetter _Cut(const char* name, list_t<Ref<ComplexCommand> >& cmdlist, bool isRemove)
    {
        CommandSetter setter;
        ByteArray nameArray(name);
        ByteArray cmdName;
        size_t index = 0;
        list_t<Ref<ComplexCommand> >::iterator itr;

        while(index != SIZE_EOF)
        {
            if(cmdlist.size() < 1)
                break;

            index = StringConvert::IndexOf(nameArray, ';');
            cmdName = nameArray.SubArray(0, index);
            // 已经没有分隔符
            if(cmdName.IsEmpty())
                break;
            for(itr = cmdlist.begin();itr != cmdlist.end(); ++itr)
            {
                ByteArray srcName((*itr)->Name());
                if(_Compare(srcName, cmdName))
                {
                    setter._cmd_pool.push_back(*itr);
                    if(isRemove)
                    {
                        cmdlist.erase(itr);
                    }
                    break;
                }
            }
            nameArray = nameArray.SubArray(index + 1);
        }
        setter._refCollection = _refCollection;
        return setter;
    }
public:
    CommandSetter() {}
    CommandSetter(CommandCollection& collection)
    {
        _refCollection = collection;
    }
    virtual EnumeratorType GetEnumerator() const
    {
        EnumeratorType enumer;
        typedef ListReadOnlyEnumerator<list_t<Ref<ComplexCommand> > > ListReadOnlyEnumeratorType;
        ListReadOnlyEnumeratorType* pNull = NULL;
        enumer.Create(_cmd_pool, pNull);
        return enumer;
    }
    inline CommandSetter& Set(CommandCollection& collection)
    {
        _refCollection = collection;
        return (*this);
    }
    inline CommandSetter& Reset()
    {
        _refCollection.Free();
        return (*this);
    }
    /**
     * @brief 新建立命令并返回新建的命令集合(每个命令以;号分隔)
     * @warning 必须引用CommandCollection
     */
    CommandSetter New(const char* name)
    {
        CommandSetter setter;
        if(!_refCollection.IsNull())
        {
            setter._refCollection = _refCollection;

            list_t<string> cmdlist;
            StringHelper::Split(name, cmdlist, ';');
            list_t<string>::iterator itr;
            Ref<ComplexCommand> complexCmd;
            for(itr = cmdlist.begin();itr != cmdlist.end(); ++itr)
            {
                complexCmd = _refCollection->Registe(itr->c_str());
                setter._cmd_pool.push_back(complexCmd);
            }
        }
        return setter;
    }
    /// 从CommandCollection中提取出命令并返回一个新的集合
    CommandSetter Cut(const char* name)
    {
        if(_refCollection.IsNull())
            return (*this);

        list_t<Ref<ComplexCommand> > cmdlist;
        _refCollection->GetCommand("", cmdlist);
        return _Cut(name, cmdlist, true);
    }
    /// 提取相同分组下的命令并返回一个新的集合
    CommandSetter Filter(const char* group)
    {
        // 查找以 group 开头的命令,后续的名称中不再包含 . 号分隔符
        CommandSetter setter;
        ByteArray cmdName;
        ByteArray grpName(group);

        list_t<Ref<ComplexCommand> >::iterator itr;
        for(itr = _cmd_pool.begin();itr != _cmd_pool.end(); ++itr)
        {
            cmdName = ByteArray((*itr)->Name());
            if(!StringConvert::StartWith(cmdName, grpName, true))
                continue;
            if(grpName.GetLength() < 1)
            {
                if(cmdName[0] != '.' && StringConvert::ContainsChar(cmdName, '.'))
                    continue;
            }
            else
            {
                cmdName = cmdName.SubArray(grpName.GetLength());
                if(cmdName.GetLength() > 0)
                {
                    if(cmdName[0] != '.')
                        continue;
                    if(StringConvert::ContainsChar(cmdName.SubArray(1), '.'))
                        continue;
                }
            }
            setter._cmd_pool.push_back(*itr);
        }
        setter._refCollection = _refCollection;
        return setter;
    }
    /**
     * @brief 查找指定名称的命令(按相似度进行匹配)
     * @warning 优先在当前命令中查找,没找到则在CommandConnection中查找
     */
    Ref<ComplexCommand> LookUp(const char* name) const
    {
        Ref<ComplexCommand> complexCmd = _LookUp(name, _cmd_pool);
        if(!complexCmd.IsNull())
            return complexCmd;

        list_t<Ref<ComplexCommand> > cmdlist;
        if(!_refCollection.IsNull())
        {
            // 单独提取处理,已过滤传入的重复命令
            _refCollection->GetCommand("", cmdlist);
        }
        return _LookUp(name, cmdlist);
    }
    /// 在当前命令中查找
    Ref<ComplexCommand> Seek(const char* name) const
    {
        return _LookUp(name, _cmd_pool);
    }
    /**
     * @brief 从当前命令中中剪切出命令并返回一个新的集合
     * 
     * @param [in] name 需要剪切出的命令名称(每个命令之间以;号分隔)
     * @param [in] isRemove [default:true] 是否删除剪切出的命令
     */
    inline CommandSetter Slice(const char* name, bool isRemove = true)
    {
        return _Cut(name, _cmd_pool, isRemove);
    }
    /// 选择CommandCollection中的所有命令
    CommandSetter& All(const char* name = NULL)
    {
        if(_refCollection.IsNull())
            return (*this);

        if(_cmd_pool.size() < 1)
        {
            _refCollection->GetCommand(name, _cmd_pool);
            return (*this);
        }
        
        list_t<Ref<ComplexCommand> > cmdlist;
        _refCollection->GetCommand(name, cmdlist);
        return Import(cmdlist);
    }
    /// 清空所有当前分组中的命令
    CommandSetter& Clear()
    {
        _cmd_pool.clear();
        return (*this);
    }
    /// 从CommandCollection中获取指定名称的命令,每个命令之间以;号分隔
    CommandSetter& Get(const char* name)
    {
        return Import(Cut(name)._cmd_pool);
    }
    /// 从CommandSetter中获取命令
    CommandSetter& Get(const CommandSetter& collection)
    {
        return Import(collection._cmd_pool);
    }
    /// 忽略具有相似名称的命令
    CommandSetter& Ignore(const char* name, CommandSetter* pIgnoreSetter = NULL)
    {
        list_t<Ref<ComplexCommand> >::iterator itr;
        ByteArray nameArray(name);
        for(itr = _cmd_pool.begin();itr != _cmd_pool.end(); ++itr)
        {
            if(StringConvert::Contains((*itr)->Name(), nameArray, true))
            {
                if(pIgnoreSetter != NULL)
                {
                    pIgnoreSetter->_cmd_pool.push_back(*itr);
                }
                itr = list_helper<Ref<ComplexCommand> >::erase(_cmd_pool, itr);
            }
        }
        return (*this);
    }
    /// 剔除指定名称的命令(每个命令之间以;号分隔)
    CommandSetter& Except(const char* name, CommandSetter* pExceptSetter = NULL)
    {
        list_t<ByteArray> namelist;
        ByteArray nameArray(name);
        size_t index = StringConvert::IndexOf(nameArray, ';');
        while(index != SIZE_EOF)
        {
            namelist.push_back(nameArray.SubArray(0, index));
            nameArray = nameArray.SubArray(index + 1);
            index = StringConvert::IndexOf(nameArray, ';');
        }
        namelist.push_back(nameArray);
        
        list_t<Ref<ComplexCommand> >::iterator itr;
        list_t<ByteArray>::iterator nameItr;
        for(itr = _cmd_pool.begin();itr != _cmd_pool.end(); ++itr)
        {
            for(nameItr = namelist.begin();nameItr != namelist.end(); ++nameItr)
            {
                if(StringConvert::Compare((*itr)->Name(), *nameItr, true))
                {
                    if(pExceptSetter != NULL)
                    {
                        pExceptSetter->_cmd_pool.push_back(*itr);
                    }
                    itr = list_helper<Ref<ComplexCommand> >::erase(_cmd_pool, itr);
                    list_helper<ByteArray>::erase(namelist, nameItr);
                    break;
                }
            }
        }

        return (*this);
    }
    /// 导入外部的命令
    CommandSetter& Import(const Ref<ComplexCommand> cmd)
    {
        if(cmd.IsNull())
            return (*this);

        // 重复性校验
        list_t<Ref<ComplexCommand> >::iterator itr;
        ByteArray nameArray(cmd->Name());
        bool isContains = false;
        for(itr = _cmd_pool.begin();itr != _cmd_pool.end(); ++itr)
        {
            ByteArray cmdName((*itr)->Name());
            if(StringConvert::Compare(nameArray, cmdName, true))
            {
                isContains = true;
                break;
            }
        }
        if(!isContains)
        {
            _cmd_pool.push_back(cmd);
        }
        return (*this);
    }
    /// 导入外部命令
    CommandSetter& Import(const list_t<Ref<ComplexCommand> >& cmdlist)
    {
        // 重复性校验
        list_t<Ref<ComplexCommand> >::const_iterator cmdItr;
        for(cmdItr = cmdlist.begin();cmdItr != cmdlist.end(); ++cmdItr)
        {
            Import(*cmdItr);
        }
        return (*this);
    }
    /// 导出命令
    CommandSetter& Export(CommandCollection& collection)
    {
        CommandCollection::RegisteCommand(collection, _cmd_pool);
        return (*this);
    }
    /// 导出命令
    CommandSetter& Export(list_t<Ref<ComplexCommand> >& cmdlist)
    {
        cmdlist += _cmd_pool;
        return (*this);
    }
    /// 注册一组新的命令
    CommandSetter& Registe(const CommandSetter& setter)
    {
        if(_refCollection.IsNull())
            return (*this);
        CommandCollection::RegisteCommand(*_refCollection, setter._cmd_pool);
        _cmd_pool += setter._cmd_pool;
        return (*this);
    }
    /// 注册一组新的命令,并以新的名称分组
    CommandSetter& Registe(const char* sName, const CommandSetter& setter)
    {
        ByteArray spaceName(sName);
        if(spaceName.IsEmpty())
            return Registe(setter);

        if(_refCollection.IsNull())
            return (*this);

        ByteBuilder name(8);
        Ref<ComplexCommand> complexCmd;
        CommandSetter::EnumeratorType enumer = setter.GetEnumerator();
        while(enumer.MoveNext())
        {
            name.Clear();
            name += spaceName;
            name += static_cast<byte>('.');
            name += enumer.Current()->Name();
            // 重新命名
            complexCmd = (*_refCollection).Registe(name.GetString());
            complexCmd->Bind(enumer.Current());
            _cmd_pool.push_back(complexCmd);
        }
        return (*this);
    }
    /// 从CommandCollection中解注册命令(每个命令之间以;号分隔)
    CommandSetter& Unregiste(const char* name)
    {
        if(_refCollection.IsNull())
            return (*this);

        Ref<ComplexCommand> complexCmd;
        ByteArray nameArray(name);
        size_t index = StringConvert::IndexOf(nameArray, ';');
        while(index != SIZE_EOF)
        {
            _refCollection->Unregiste(nameArray.SubArray(0, index));
            
            nameArray = nameArray.SubArray(index + 1);
            index = StringConvert::IndexOf(nameArray, ';');
        }
        return (*this);
    }
    /// 注册命令到CommandCollection中
    CommandSetter& UniqueRegiste(const CommandSetter& setter)
    {
        if(!_refCollection.IsNull())
        {
            CommandCollection::UniqueRegisteCommand(*_refCollection, setter._cmd_pool);
        }
        return (*this);
    }
    /// 为当前命令绑定命令
    CommandSetter& Bind(const CommandSetter& cmds, const IStringArguments& sArg, ComplexCommand::CommandOption option = ComplexCommand::RunOnSuccess)
    {
        list_t<Ref<ComplexCommand> >::iterator itr;
        list_t<Ref<ComplexCommand> >::const_iterator cmdItr;
        for(itr = _cmd_pool.begin();itr != _cmd_pool.end(); ++itr)
        {
            for(cmdItr = cmds._cmd_pool.begin();cmdItr != cmds._cmd_pool.end(); ++cmdItr)
            {
                (*itr)->Bind(*cmdItr, sArg, option);
            }
        }
        return (*this);
    }
    /// 为当前命令绑定命令
    CommandSetter& Bind(const CommandSetter& cmds, ComplexCommand::CommandOption option = ComplexCommand::RunOnSuccess)
    {
        list_t<Ref<ComplexCommand> >::iterator itr;
        list_t<Ref<ComplexCommand> >::const_iterator cmdItr;
        for(itr = _cmd_pool.begin();itr != _cmd_pool.end(); ++itr)
        {
            for(cmdItr = cmds._cmd_pool.begin();cmdItr != cmds._cmd_pool.end(); ++cmdItr)
            {
                (*itr)->Bind(*cmdItr, option);
            }
        }
        return (*this);
    }
    /// 为当前命令绑定前置命令
    CommandSetter& PrefixBind(const CommandSetter& cmds, const IStringArguments& sArg, ComplexCommand::CommandOption option = ComplexCommand::RunOnSuccess)
    {
        list_t<Ref<ComplexCommand> >::iterator itr;
        list_t<Ref<ComplexCommand> >::const_reverse_iterator cmdItr;
        for(itr = _cmd_pool.begin();itr != _cmd_pool.end(); ++itr)
        {
            for(cmdItr = cmds._cmd_pool.rbegin();cmdItr != cmds._cmd_pool.rend(); ++cmdItr)
            {
                (*itr)->PrefixBind(*cmdItr, sArg, option);
            }
        }
        return (*this);
    }
    /// 为当前命令绑定前置命令
    CommandSetter& PrefixBind(const CommandSetter& cmds, ComplexCommand::CommandOption option = ComplexCommand::RunOnSuccess)
    {
        list_t<Ref<ComplexCommand> >::iterator itr;
        list_t<Ref<ComplexCommand> >::const_reverse_iterator cmdItr;
        for(itr = _cmd_pool.begin();itr != _cmd_pool.end(); ++itr)
        {
            for(cmdItr = cmds._cmd_pool.rbegin();cmdItr != cmds._cmd_pool.rend(); ++cmdItr)
            {
                (*itr)->PrefixBind(*cmdItr, option);
            }
        }
        return (*this);
    }
    /// 返回命令数目
    inline size_t Count() const
    {
        return _cmd_pool.size();
    }
    /// 返回CommandCollection引用是否为空
    inline bool IsNull() const
    {
        return _refCollection.IsNull();
    }
    /// 返回是否引用指定的CommandCollection
    inline bool IsRef(CommandCollection& collection)
    {
        return _refCollection == collection;
    }
};
//--------------------------------------------------------- 
/// 基于ICommandHandler::Arguments的命令运行器
class CommandActuator : public LoggerBehavior
{
protected:
    Ref<CommandCollection> _refCollection;
    StringArguments _arg;
    StringArguments _rlt;
public:
    CommandActuator() {}
    CommandActuator(CommandCollection& collection)
    {
        Set(collection);
    }
    CommandActuator& Set(CommandCollection& collection)
    {
        _refCollection = collection;
        return (*this);
    }
    CommandActuator& Set(const CommandActuator& actuator)
    {
        _refCollection = actuator._refCollection;
        return (*this);
    }
    /**
     * @brief 重置运行状态
     * @date 2016-10-12 12:42
     * 
     * @param [in] isClearArg [default:true] 是否清空输入
     * @param [in] isClearRlt [default:true] 是否清空输出
     */
    CommandActuator& Reset(bool isClearArg = true, bool isClearRlt = true)
    {
        if(isClearArg)
        {
            ArgClear();
        }
        if(isClearRlt)
        {
            RltClear();
        }
        return (*this);
    }
    /// 清空参数
    CommandActuator& ArgClear()
    {
        _arg.Clear();
        return (*this);
    }
    /// 清空结果
    CommandActuator& RltClear()
    {
        _rlt.Clear();
        return (*this);
    }
    /// 返回对参数的引用
    inline ICommandHandler::Arguments& Arg()
    {
        return _arg;
    }
    /// 返回结果的引用
    inline ICommandHandler::Arguments& Result()
    {
        return _rlt;
    }
    /// 增加命令参数 T
    template<class T>
    CommandActuator& Arg(const string& key, const T& val)
    {
        _arg.Put(key, ArgConvert::ToString(val));
        return (*this);
    }
    /// 增加命令参数
    CommandActuator& Arg(const string& key, const string& val)
    {
        _arg.Put(key, val);
        return (*this);
    }
    /// 增加命令参数
    CommandActuator& Arg(const ICommandHandler::Arguments& arg)
    {
        StringArguments::CopyTo(arg, _arg);
        return (*this);
    }
    /**
     * @brief 执行命令
     * @date 2016-10-04 22:49
     * 
     * @param [in] name 需要执行的命令名称
     * @param [in] isRltToArg [default:false] 是否需要将结果作为参数
     * @param [out] pIsOK [default:NULL] 命令运行结果
     * @param [out] pIsRun [default:NULL] 是否执行过该命令
     */
    CommandActuator& Run(const char* name, bool isRltToArg = false, bool* pIsOK = NULL, bool* pIsRun = NULL)
    {
        bool bRlt = false;
        bRlt = Run(name, _arg, _rlt, pIsRun);
        // 保存结果作为参数
        if(bRlt && isRltToArg)
        {
            StringArguments::CopyTo(_rlt, _arg);
        }
        if(pIsOK != NULL)
        {
            (*pIsOK) = bRlt;
        }
        return (*this);
    }
    /// 使用外部传入的参数运行命令
    bool Run(const char* name, IStringArguments& arg, IStringArguments& rlt, bool* pIsRun = NULL)
    {
        bool bRlt = false;
        bool bRun = true;
        if(!_refCollection.IsNull())
        {
            LOGGER(_log << "LookUp:<" << _strput(name) << ">\n");
            CommandSetter setter(*_refCollection);
            Ref<ComplexCommand> complexCmd = setter.LookUp(name);
            if(!complexCmd.IsNull())
            {
                LOGGER(complexCmd->Print(_log));
                bRlt = complexCmd->OnCommand(arg, rlt);
                LOGGER(_log << "Return:<" << bRlt << ">\n");
            }
            else
            {
                bRun = false;
                LOGGER(_log.WriteLine("Command is null."));
            }
        }
        if(pIsRun != NULL)
        {
            (*pIsRun) = bRun;
        }
        return bRlt;
    }
    /// 运行指定的命令
    inline bool OnCall(const char* name, bool* pIsRun = NULL)
    {
        bool bOK = false;
        Run(name, false, &bOK, pIsRun);
        return bOK;
    }
    /// 反射接口
    template<class T>
    Ref<T> Reflect(const char* key)
    {
        Ref<T> refnull;
        if(_refCollection.IsNull())
            return refnull;

        ByteArray keyName(key);
        if(keyName.IsEmpty())
            return refnull;

        StringArguments arg;
        StringArguments rlt;

        CommandSetter setter(*_refCollection);
        Ref<ComplexCommand> complexCmd = setter.LookUp(key);
        if(complexCmd.IsNull() || !complexCmd->OnCommand(arg, rlt))
            return refnull;
        // 截取最后的类型名称
        size_t index = StringConvert::LastIndexOf(keyName, '.');
        if(index != SIZE_EOF)
            keyName = keyName.SubArray(index + 1);
        return CommandHelper::InterfaceRef<T>(rlt, keyName.GetString());
    }
    /// 返回运行器是否为空
    inline bool IsNull() const
    {
        return _refCollection.IsNull();
    }
};
//--------------------------------------------------------- 
/// 常用的一些脚本命令
class CommandScript
{
protected:
    CommandScript() {}
public:
/// 将参数作为结果
    static LC_CMD_METHOD(ARGtoRLT)
    {
        StringArguments::CopyTo(arg, rlt);
        return true;
    }
    /// 清空参数
    static LC_CMD_METHOD(ClearARG)
    {
        StringArguments::Clear(arg);
        return true;
    }
    /// 清空结果
    static LC_CMD_METHOD(ClearRLT)
    {
        StringArguments::Clear(rlt);
        return true;
    }
    /// 将结果作为参数
    static LC_CMD_METHOD(RLTtoARG)
    {
        StringArguments::CopyTo(rlt, arg);
        return true;
    }
    /// 返回成功的结果
    static LC_CMD_METHOD(SuccessRET) { return true; }
    /// 返回失败的结果
    static LC_CMD_METHOD(ErrorRET) { return false; }
};
//--------------------------------------------------------- 
/**
 * @brief 支持if条件判断的命令
 * @date 2017-12-18 17:14
 */
class IfCommand : public ICommandHandler, public RefObject
{
protected:
    list_t<Ref<ICommandHandler> > _ifCmds;
    list_t<Ref<ICommandHandler> > _ifOkCmds;

    Ref<ICommandHandler> _elseCmd;
    Ref<ICommandHandler> _finalCmd;
public:
    IfCommand() {}
    virtual ~IfCommand() {}
    inline IfCommand& If(Ref<ICommandHandler> ifCmd, Ref<ICommandHandler> okCmd)
    {
        _ifCmds.push_front(ifCmd);
        _ifOkCmds.push_front(okCmd);
        return (*this);
    }
    inline IfCommand& ElseIf(Ref<ICommandHandler> ifCmd, Ref<ICommandHandler> okCmd)
    {
        _ifCmds.push_back(ifCmd);
        _ifOkCmds.push_back(okCmd);
        return (*this);
    }
    inline IfCommand& Else(Ref<ICommandHandler> elseCmd)
    {
        _elseCmd = elseCmd;
        return (*this);
    }
    inline IfCommand& Final(Ref<ICommandHandler> finalCmd)
    {
        _finalCmd = finalCmd;
        return (*this);
    }
    inline void Clear()
    {
        _ifCmds.clear();
        _ifOkCmds.clear();
        _elseCmd.Free();
        _finalCmd.Free();
    }
    /// 执行命令
    virtual bool OnCommand(Arguments& arg, Arguments& rlt)
    {
        list_t<Ref<ICommandHandler> >::iterator ifItr;
        list_t<Ref<ICommandHandler> >::iterator okItr;

        bool bOK = true;
        bool isRunIf = false;
        size_t index = 0;
        for(ifItr = _ifCmds.begin();ifItr != _ifCmds.end(); ++ifItr)
        {
            ++index;
            if(ifItr->IsNull())
                continue;
            bOK = (*ifItr)->OnCommand(arg, rlt);
            if(bOK)
            {
                isRunIf = true;
                okItr = list_helper<Ref<ICommandHandler> >::index_of(_ifOkCmds, index);
                if(!okItr->IsNull())
                {
                    bOK = (*okItr)->OnCommand(arg, rlt);
                }
                break;
            }
        }
        if(!isRunIf && !_elseCmd.IsNull())
        {
            bOK = _elseCmd->OnCommand(arg, rlt);
        }
        if(!_finalCmd.IsNull())
        {
            _finalCmd->OnCommand(arg, rlt);
        }
        return bOK;
    }
    /// 命令是否有效
    virtual bool IsRunable() const { return true; }
};
//--------------------------------------------------------- 
/**
 * @brief 判断是否失败的命令
 * @date 2017-12-18 21:54
 */
class IsResultFailedCommand : public ICommandHandler, public RefObject
{
protected:
    Ref<ICommandHandler> _cmd;
public:
    IsResultFailedCommand(Ref<ICommandHandler> cmd) { _cmd = cmd; }
    IsResultFailedCommand() {}
    virtual ~IsResultFailedCommand() {}

    inline IsResultFailedCommand& IsResultFailed(Ref<ICommandHandler> cmd)
    {
        _cmd = cmd;
        return (*this);
    }
    /// 执行命令
    virtual bool OnCommand(Arguments& arg, Arguments& rlt)
    {
        if(_cmd.IsNull())
            return true;
        return !(_cmd->OnCommand(arg, rlt));
    }
    /// 命令是否有效
    virtual bool IsRunable() const { return !_cmd.IsNull(); }
};
//--------------------------------------------------------- 
/// 执行内部命令的脚本封装器
class CommandScriptActuator : public CommandCollection
{
protected:
    StringArguments _arg;
    StringArguments _rlt;
    Ref<ComplexCommand> _scriptCmd;
    LOGGER(Ref<ComplexCommand> _scriptLog);
    size_t _scriptCount;

    /// 将外部参数导入
    LC_CMD_METHOD(Import)
    {
        StringArguments::CopyTo(arg, _arg);
        return true;
    }
    /// 将输出参数作为输入参数
    LC_CMD_METHOD(RltToArg)
    {
        StringArguments::CopyTo(_rlt, _arg);
        return true;
    }
    /// 将输入参数作为结果
    LC_CMD_METHOD(ArgToRlt)
    {
        StringArguments::CopyTo(_arg, _rlt);
        return true;
    }
    /// 执行子命令
    LC_CMD_METHOD(OnScript)
    {
        return _scriptCmd->OnCommand(arg, rlt);
    }
    /// 将内部参数输出
    LC_CMD_METHOD(Result)
    {
        StringArguments::CopyTo(_rlt, rlt);
        return true;
    }
    /// 清空输入
    LC_CMD_METHOD(ArgClear)
    {
        _arg.Clear();
        return true;
    }
    /// 清空输出
    LC_CMD_METHOD(RltClear)
    {
        _rlt.Clear();
        return true;
    }
    /// 使用内部参数运行绑定的命令
    LC_CMD_METHOD(Run)
    {
        size_t index = arg["Index"].To<size_t>(0);
        if(index < 1)
            return false;

        list_t<ComplexCommand>::iterator itr = list_helper<ComplexCommand>::index_of(_cmd_collection, index);
        if(itr == _cmd_collection.end())
            return false;
        return itr->OnCommand(_arg, _rlt);
    }
    /// 做日志输出
    LC_CMD_METHOD(Log)
    {
        return true;
    }

    /// 生成一个新的命令
    Ref<ComplexCommand> _NewCmd(const char* name)
    {
        string cmdName = "CommandScriptActuator::";
        cmdName += _strput(name);
        cmdName += "[";
        cmdName += ArgConvert::ToString(_scriptCount);
        cmdName += "]";

        ++_scriptCount;

        return Registe(cmdName.c_str());
    }
    /// 生成新的脚本命令 
    Ref<ComplexCommand> _Run(const char* name, ComplexCommand::CommandOption option)
    {
        size_t index = _cmd_collection.size();
        StringArguments bindArg;
        bindArg.Put("Index", ArgConvert::ToString(index));
        if(!_is_empty_or_null(name))
        {
            bindArg.Put("Name", name);
        }
        else
        {
            name = "Script";
        }
        _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, Run), bindArg, option);
        return _NewCmd(name);
    }
public:
    CommandScriptActuator()
    {
        Reset();
    }
    /// 生成一个新的脚本命令
    Ref<ComplexCommand> MakeCmd(Ref<ICommand> cmd, const char* name = NULL)
    {
        Ref<ComplexCommand> complexCmd = _NewCmd(name);
        complexCmd->Bind(cmd, ComplexCommand::RunOnSuccess);
        return complexCmd;
    }
    /// 生成一个新的脚本命令
    Ref<ComplexCommand> MakeCmd(Ref<ICommand> cmd, const IStringArguments& bindArg, const char* name = NULL)
    {
        Ref<ComplexCommand> complexCmd = _NewCmd(name);
        complexCmd->Bind(cmd, bindArg, ComplexCommand::RunOnSuccess);
        return complexCmd;
    }
    /// 重置为初始状态
    CommandScriptActuator& Reset()
    {
        CommandCollection::Clear();

        _scriptCount = 0;
        _scriptCmd = Registe("Script");
        LOGGER(_scriptLog = Registe("BindCmd"));
        
        Ref<ComplexCommand> cmd = _RegisteCMD(CommandScriptActuator, OnScript);

        LOGGER(Ref<Command> logCmd = _MakeCMD(CommandScriptActuator, Log);
        cmd->Bind(logCmd, ComplexCommand::RunOnEOF);
        cmd->Bind(_scriptCmd);
        cmd->Bind(logCmd, ComplexCommand::RunOnEOF);
        cmd->Bind(_scriptLog));
        // 默认注册上清空的命令
        Clear(true, true);

        return (*this);
    }
    /// 清空参数
    CommandScriptActuator& Clear(bool isClearArg, bool isClearRlt)
    {
        if(isClearArg)
            _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, ArgClear));
        if(isClearRlt)
            _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, RltClear));
        return (*this);
    }
    /// 导入外部的Arg
    CommandScriptActuator& Import(bool isSaveArg = false)
    {
        if(!isSaveArg)
        {
            _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, ArgClear));
        }
        _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, Import));
        return (*this);
    }
    /// 将内部结果输出为内部参数
    CommandScriptActuator& ToArg(bool isSavaRlt = false, bool isSaveArg = false)
    {
        if(!isSaveArg)
        {
            _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, ArgClear));
        }
        _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, RltToArg));
        if(!isSavaRlt)
        {
            _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, RltClear));
        }
        return (*this);
    }
    /// 将内部参数作为结果
    CommandScriptActuator& ToRlt(bool isSaveArg = false, bool isSaveRlt = false)
    {
        if(!isSaveRlt)
        {
            _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, RltClear));
        }
        _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, ArgToRlt));
        if(!isSaveArg)
        {
            _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, ArgClear));
        }
        return (*this);
    }
    /// 导出内部的Rlt
    CommandScriptActuator& Export(bool isSaveRlt = false)
    {
        _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, Result));
        if(!isSaveRlt)
        {
            _scriptCmd->Bind(_MakeCMD(CommandScriptActuator, RltClear));
        }
        return (*this);
    }
    /// 注册需要执行的命令
    CommandScriptActuator& Run(const Ref<ICommand> scriptCmd, ComplexCommand::CommandOption option = ComplexCommand::RunOnSuccess)
    {
        const char* name = NULL;
        if(!scriptCmd.IsNull())
        {
            name = scriptCmd->Name();
        }
        Ref<ComplexCommand> complexCmd = _Run(name, option);
        complexCmd->Bind(scriptCmd, option);
        LOGGER(_scriptLog->Bind(scriptCmd, option));
        return (*this);
    }
    /// 注册需要执行的命令
    CommandScriptActuator& Run(const Ref<ICommand> scriptCmd, const IStringArguments& bindArg, ComplexCommand::CommandOption option = ComplexCommand::RunOnSuccess)
    {
        const char* name = NULL;
        if(!scriptCmd.IsNull())
        {
            name = scriptCmd->Name();
        }
        Ref<ComplexCommand> complexCmd = _Run(name, option);
        complexCmd->Bind(scriptCmd, bindArg, option);
        LOGGER(_scriptLog->Bind(scriptCmd, bindArg, option));
        return (*this);
    }
    /// 注册需要执行的命令
    CommandScriptActuator& Run(const Ref<ICommand> scriptCmd, IStringArgParser& parser, const char* sArg, 
        ComplexCommand::CommandOption option = ComplexCommand::RunOnSuccess)
    {
        if(sArg == NULL)
            return Run(scriptCmd, option);

        StringArguments arg;
        parser.Parse(sArg, arg);
        return Run(scriptCmd, arg, option);
    }
    /// 返回生成的脚本Setter
    CommandSetter Script(const char* scriptName = NULL)
    {
        return CommandSetter(*this).Import(ScriptCmd(scriptName));
    }
    /// 返回生成的脚本命令
    inline Ref<ComplexCommand> ScriptCmd(const char* scriptName = NULL)
    {
        const char NAME[] = "OnScript";
        Ref<ComplexCommand> scriptCmd = LookUp(NAME);
        if(_is_empty_or_null(scriptName))
            return scriptCmd;

        Ref<ComplexCommand> cmd = Registe(scriptName);
        cmd->Bind(scriptCmd);
        return cmd;
    }
};
//--------------------------------------------------------- 
/// 执行ICommandDriver的命令
template<class TArgParser>
class CommandDriverScriptActuator : public CommandCollection
{
protected:
    Ref<ICommandDriver> _cmdDriver;
    TArgParser _parser;
    string _cmd;

    LC_CMD_METHOD(OnScript)
    {
        if(_cmdDriver.IsNull())
            return false;
        ByteBuilder sArg(32);
        ByteBuilder sRlt(32);
        _parser.Parse(sArg, arg);
        if(!_cmdDriver->TransmitCommand(_cmd.c_str(), sArg, sRlt))
            return false;
         _parser.ToString(rlt, sRlt);
         return true;
    }
public:
    CommandDriverScriptActuator() {}
    Ref<ComplexCommand> Script(Ref<ICommandDriver>& cmdDriver, const char* sCmd)
    {
        _cmdDriver = cmdDriver;
        _cmd = _strput(sCmd);

        CommandCollection::Clear();

        Ref<ComplexCommand> complexCmd = Registe(sCmd);
        complexCmd->Bind(_MakeCMD(CommandDriverScriptActuator, OnScript));
        return complexCmd;
    }
    inline bool IsNull() const
    {
        return _cmdDriver.IsNull();
    }
};
//--------------------------------------------------------- 
/// 执行LastErr命令获取错误信息
class CommandLastErrActuator : public ILastErrBehavior, public RefObject
{
protected:
    CommandCollection* _pCollection;
    Ref<ComplexCommand> _cmdLastErr;
    Ref<ComplexCommand> _cmdResetErr;
    Ref<ILastErrBehavior> _refBehavior;
    string _err_msg;
    bool _RunLastErr(int& err, string* pMsg) const
    {
        if(_cmdLastErr.IsNull())
            return false;

        StringArguments arg;
        StringArguments rlt;
        Ref<ComplexCommand> cmd = _cmdLastErr;
        if(!cmd->OnCommand(arg, rlt))
            return false;

        err = rlt["CODE"].To<int>(DeviceError::Success);
        if(pMsg != NULL)
        {
            (*pMsg) = rlt["MSG"].To<string>();
        }
        return true;
    }
    bool _RunResetErr()
    {
        if(_cmdResetErr.IsNull())
            return false;

        StringArguments arg;
        StringArguments rlt;
        return _cmdResetErr->OnCommand(arg, rlt);
    }
public:
    CommandLastErrActuator()
    {
        _pCollection = NULL;
    }
    CommandLastErrActuator(CommandCollection& collection)
    {
        Extract(collection);
    }
    /// 提取适配 ILastErrBehavior 接口
    bool Extract(CommandCollection& collection)
    {
        _pCollection = &collection;
        _refBehavior.Free();
        _cmdLastErr.Free();

        const char BehaviorKey[] = "ILastErrBehavior";
        const char LastErrKey[] = "LastError";
        const char ResetErrKey[] = "ResetError";

        StringArguments arg;
        StringArguments rlt;

        // 查找命令
        if(_cmdLastErr.IsNull())
        {
            Ref<ComplexCommand> complexCmd = _pCollection->LookUp(BehaviorKey);
            if(complexCmd.IsNull())
            {
                // 尝试查找命令 LastErr
                complexCmd = _pCollection->LookUp(LastErrKey);
                if(complexCmd.IsNull())
                    return false;
                _cmdLastErr = complexCmd;
                // ResetError 命令可以不支持
                _cmdResetErr = _pCollection->LookUp(ResetErrKey);
            }
            else
            {
                // 支持 ILastErrBehavior 接口,从接口中进行查找
                if(!complexCmd->OnCommand(arg, rlt))
                    return false;
                _refBehavior = CommandReflectArg(ILastErrBehavior, rlt);
                if(_refBehavior.IsNull())
                    return false;
            }
        }
        return true;
    }
    inline bool IsNull() const
    {
        return _cmdLastErr.IsNull() && _refBehavior.IsNull();
    }

    virtual int GetLastErr() const
    {
        if(!_refBehavior.IsNull())
            return _refBehavior->GetLastErr();
        // 从命令LastErr中获取错误信息
        int err = DeviceError::Success;
        _RunLastErr(err, NULL);
        return err;
    }
    virtual const char* GetErrMessage()
    {
        if(!_refBehavior.IsNull())
            return _refBehavior->GetErrMessage();

        int err = DeviceError::Success;
        _RunLastErr(err, &_err_msg);
        return _err_msg.c_str();
    }
    virtual void ResetErr()
    {
        if(!_refBehavior.IsNull())
        {
            _refBehavior->ResetErr();
        }
        else
        {
            _RunResetErr();
        }
        _err_msg = "";
    }
};
//--------------------------------------------------------- 
/// 命令错误信息设置器
class CommandLastErrGetter
{
protected:
    Ref<IMapArguments<string, CommandCollection*> > _pItems;
    Ref<LastErrGetter> _errGetter;

    list_t<CommandLastErrActuator> _errActuactor;
    Ref<ILastErrBehavior> _Get(const char* name)
    {
        Ref<ILastErrBehavior> lastErr;
        if(_pItems.IsNull())
            return lastErr;

        CommandCollection* pVal = NULL;
        if(_pItems->Get(name, pVal))
        {
            list_t<CommandLastErrActuator>::iterator itr = _errActuactor.push_back();
            itr->Extract(*pVal);

            lastErr = (*itr);
        }
        return lastErr;
    }
public:
    CommandLastErrGetter() {}
    CommandLastErrGetter(Ref<IMapArguments<string, CommandCollection*> > cmdRunner, Ref<LastErrGetter> errGetter)
    {
        Set(cmdRunner, errGetter);
    }
    CommandLastErrGetter& Set(Ref<IMapArguments<string, CommandCollection*> > cmdRunner, Ref<LastErrGetter> errGetter)
    {
        _pItems = cmdRunner;
        _errGetter = errGetter;
        return (*this);
    }
    const bool IsValid() const
    {
        return _pItems.IsNull() || _errGetter.IsNull();
    }
    CommandLastErrGetter& MoveTo(const char* name)
    {
        if(!_errGetter.IsNull())
        {
            _errGetter->MoveTo(name);
        }
        return (*this);
    }
    CommandLastErrGetter& Add(const char* name)
    {
        if(!_errGetter.IsNull())
        {
            _errGetter->Add(name, _Get(name));
        }
        return (*this);
    }
    CommandLastErrGetter& New(const char* name)
    {
        if(!_errGetter.IsNull())
        {
            _errGetter->New(name);
        }
        return (*this);
    }
    CommandLastErrGetter& End()
    {
        if(!_errGetter.IsNull())
        {
            _errGetter->End();
        }
        return (*this);
    }
    CommandLastErrGetter& Select(const char* name)
    {
        if(!_errGetter.IsNull())
        {
            _errGetter->Select(name, _Get(name));
        }
        return (*this);
    }
    CommandLastErrGetter& Clear()
    {
        if(!_errGetter.IsNull())
        {
            _errGetter->Clear();
        }
        return (*this);
    }
};
//--------------------------------------------------------- 
/// 命令执行器
class CommandRunner :
    public CommonCmdDriver,
    public IEnumerator<ReadOnlyEnumerator<string> >
{
public:
    //----------------------------------------------------- 
    typedef ReadOnlyEnumerator<string> EnumeratorType;
    //----------------------------------------------------- 
protected:
    //----------------------------------------------------- 
    typedef MapArguments<string, CommandCollection*>::EnumeratorType MapEnumeratorType;
    //-----------------------------------------------------  
    /// 错误信息设置器
    CommandLastErrGetter _cmdErrGetter;
    /// 保存的内部对象
    list_t<CommandCollection*> _objItems;
    /// 所有子项
    MapArguments<string, CommandCollection*> _items;
    //----------------------------------------------------- 
    /// 清空所有命令
    void _Remove()
    {
        CommandCollection::Clear();
        // 注册时,命令是按照依赖顺序进行注册的,反序进行析构
        list_t<CommandCollection*>::reverse_iterator objItr;
        for(objItr = _objItems.rbegin();objItr != _objItems.rend(); ++objItr)
        {
            delete (*objItr);
        }
        _objItems.clear();
        _items.Clear();
    }
    //----------------------------------------------------- 
public:
    //----------------------------------------------------- 
    CommandRunner() : CommonCmdDriver()
    {
        _cmdErrGetter.Set(_items, _errGetter);
    }
    virtual ~CommandRunner()
    {
        _Remove();
    }
    //----------------------------------------------------- 
    virtual EnumeratorType GetEnumerator() const
    {
        typedef MapArguments<string, CommandCollection*> MapType;
        typedef MapKeyReadOnlyEnumerator<string, CommandCollection*> MapKeyEnumeratorType;

        EnumeratorType enumer;
        MapKeyEnumeratorType* pNull = NULL;
        MapEnumeratorType mapEnumer = _items.GetEnumerator();
        enumer.Create(mapEnumer, pNull);
        return enumer;
    }
    //----------------------------------------------------- 
    /// 添加新的命令组,返回新增加的集合
    template<class T>
    CommandSetter New(const string& name, Ref<T>* pRef = NULL, bool isUniqueName = false)
    {
        CommandCollection* pVal = NULL;
        bool isExist = _items.Get(name, pVal);
        // 已经包含该名称的命令集合,返回一个空的命令集
        if(isExist && isUniqueName)
        {
            return CommandSetter();
        }

        T* pCmdDriver = new T();
        CommandCollection* pCollection = pCmdDriver;
        _objItems.push_back(pCollection);

        if(pRef != NULL)
        {
            (*pRef) = (*pCmdDriver);
        }

        if(!isExist)
        {
            _items.Put(name, pCollection);
        }
        else
        {
            list_t<Ref<ComplexCommand> > cmdlist;
            pCollection->GetCommand("", cmdlist);
            CommandCollection::RegisteCommand(*pVal, cmdlist);
        }
        return CommandSetter(*pCollection);
    }
    /// 从已经注册的分组中切割出新的命令作为一个新的分组
    CommandSetter Cut(const string& name, const string& newName, const char* command)
    {
        CommandCollection* pVal = NULL;
        bool isExist = _items.Get(name, pVal);
        if(!isExist)
        {
            return CommandSetter();
        }
        CommandCollection* pNew = NULL;
        isExist = _items.Get(newName, pNew);
        if(!isExist)
        {
            pNew = new CommandCollection();
            _objItems.push_back(pNew);
            _items.Put(newName, pNew);
        }
        CommandSetter setter;
        setter.Set(*pVal);
        return setter.Cut(command);
    }
    /// 删除指定名称的命令组
    bool Remove(const string& name)
    {
        bool isRemove = false;
        MapEnumeratorType enumer = _items.GetEnumerator();
        while(enumer.MoveNext())
        {
            if(enumer.Current().Key == name)
            {
                enumer.Remove();
                isRemove = true;
                break;
            }
        }
        return isRemove;
    }
    /// 删除所有分组
    void Remove()
    {
        _Remove();
        CommandRunner::_RegisteInlineCMD();
    }
    //----------------------------------------------------- 
    /// 获取指定名称的命令集
    Ref<CommandCollection> Item(const string& name)
    {
        CommandCollection* pCollection = NULL;
        if(_items.Get(name, pCollection))
            return (*pCollection);
        return Ref<CommandCollection>();
    }
    /// 获取指定名称的命令设置器
    CommandSetter Get(const string& name)
    {
        CommandSetter setter;
        CommandCollection* pCollection = NULL;
        if(_items.Get(name, pCollection))
            setter.Set(*pCollection);
        return setter;
    }
    /// 获取指定名称的命令运行器
    CommandActuator Actuator(const string& name)
    {
        CommandActuator actuator;
        CommandCollection* pCollection = NULL;
        if(_items.Get(name, pCollection))
            actuator.Set(*pCollection);
        return actuator;
    }
    /// 获取错误信息设置器
    inline CommandLastErrGetter& LastErr()
    {
        return _cmdErrGetter;
    }
    /// 返回所有Item的数目
    inline size_t ItemCount() const
    {
        return _items.Count();
    }
    //----------------------------------------------------- 
};
//--------------------------------------------------------- 
/// 基于CommandRunner的脚本执行器
class CommandRunnerActuator : public LoggerBehavior
{
protected:
    CommandActuator _actuator;
    string _disposeCmd;
    list_t<string> _module;
    Ref<CommandRunner> _runner;
public:
    CommandRunnerActuator() {}
    CommandRunnerActuator(CommandRunner& runner)
    {
        Set(runner);
    }
    virtual ~CommandRunnerActuator()
    {
        OnFinal();
    }
    CommandRunnerActuator& Set(CommandRunner& runner)
    {
        LOGGER(LoggerBehavior::SelectLogger(runner.GetLogger()));
        LOGGER(_actuator.SelectLogger(runner.GetLogger()));

        _runner = runner;
        _actuator.Set(runner);
        _module.clear();
        return (*this);
    }
    /// 增加需要一次性Run操作的子模块,多个模块之间可以通过;号分隔
    CommandRunnerActuator& Add(const string& name)
    {
        list_t<string> modules;
        StringHelper::Split(name.c_str(), modules, ';');
        list_t<string>::iterator itr;
        for(itr = modules.begin();itr != modules.end(); ++itr)
        {
            _module.push_back(*itr);
        }
        return (*this);
    }
    /// 设置Run的子模块名称(""则会到Root),多个模块之间可以通过;号分隔
    CommandRunnerActuator& Set(const string& name)
    {
        _module.clear();
        if(name.length() > 0)
        {
            Add(name);
        }
        return (*this);
    }
    /// 选择所有模块
    CommandRunnerActuator& All()
    {
        CommandRunner::EnumeratorType enumer = (*_runner).GetEnumerator();
        _module.clear();
        while(enumer.MoveNext())
        {
            _module.push_back(enumer.Current());
        }
        return (*this);
    }
    /**
     * @brief 重置运行状态
     * @date 2016-10-12 12:42
     * 
     * @param [in] isClearArg [default:true] 是否清空输入
     * @param [in] isClearRlt [default:true] 是否清空输出
     */
    CommandRunnerActuator& Reset(bool isClearArg = true, bool isClearRlt = true)
    {
        _module.clear();
        _actuator.Reset(isClearArg, isClearRlt);
        return (*this);
    }
    /// 清空参数
    inline CommandRunnerActuator& ArgClear()
    {
        _actuator.ArgClear();
        return (*this);
    }
    /// 清空结果
    inline CommandRunnerActuator& RltClear()
    {
        _actuator.RltClear();
        return (*this);
    }
    /// 获取对参数的引用
    inline ICommandHandler::Arguments& Arg()
    {
        return _actuator.Arg();
    }
    /// 获取对参数的引用
    inline ICommandHandler::Arguments& Result()
    {
        return _actuator.Result();
    }
    /// 将当前结果作为参数导入
    inline CommandRunnerActuator& AsArg(bool isClearRlt = true)
    {
        _actuator.Arg(_actuator.Result());
        if(isClearRlt)
            _actuator.RltClear();
        return (*this);
    }
    /// 将当前参数作为结果导出
    inline CommandRunnerActuator& AsResult(bool isClearArg = true)
    {
        StringArguments::CopyTo(_actuator.Arg(), _actuator.Result());
        if(isClearArg)
            _actuator.ArgClear();
        return (*this);
    }
    /// 增加命令参数 T
    template<class T>
    inline CommandRunnerActuator& Arg(const string& key, const T& val)
    {
        _actuator.Arg(key, ArgConvert::ToString(val));
        return (*this);
    }
    /// 增加命令参数
    inline CommandRunnerActuator& Arg(const string& key, const string& val)
    {
        _actuator.Arg(key, val);
        return (*this);
    }
    /// 增加命令参数
    inline CommandRunnerActuator& Arg(const ICommandHandler::Arguments& arg)
    {
        _actuator.Arg(arg);
        return (*this);
    }
    /// 增加命令参数
    inline CommandRunnerActuator& Arg(IStringArgParser& parser, const char* sArg)
    {
        StringArguments arg;
        parser.Parse(sArg, arg);
        return Arg(arg);
    }
    /// 将参数导出
    inline CommandRunnerActuator& Export(ICommandHandler::Arguments& arg)
    {
        StringArguments::CopyTo(_actuator.Arg(), arg);
        return (*this);
    }
    /**
     * @brief 执行命令
     * @date 2016-10-04 22:49
     * 
     * @param [in] name 需要执行的命令名称
     * @param [in] isRltToArg [default:false] 是否将结果保存为参数
     * @param [out] pIsOK [default:NULL] 命令运行结果
     * @param [out] pHasRun [default:NULL] 是否运行过该命令
     */
    CommandRunnerActuator& Run(const char* name, bool isRltToArg = false, bool* pIsOK = NULL, bool* pHasRun = NULL)
    {
        LOG_FUNC_NAME();
        LOGGER(_log.WriteLine("/=------------");
        _log << "Arguments:[" << _actuator.Arg().Count() << "]\n";
        size_t width = 0;
        IStringArguments::EnumeratorType enumer = _actuator.Arg().GetEnumerator();
        while(enumer.MoveNext())
        {
            width = _max(enumer.Current().Key.length(), width);
            _log << _left_width(enumer.Current().Key, width) << " : <" << enumer.Current().Value << ">\n";
        }
        _log.WriteLine("/=------------"));

        bool bIsOK = false;
        bool bHasRun = false;
        if(_runner.IsNull())
        {
            if(pIsOK != NULL)
            {
                (*pIsOK) = bIsOK;
            }
            if(pHasRun != NULL)
            {
                (*pHasRun) = bHasRun;
            }
            LOGGER(_log.WriteLine("CommandRunner<T> is null."));
            return (*this);
        }

        if(_module.size() < 1)
        {
            LOGGER(_log << "Runner OnCommand:<" << _strput(name) << ">\n");
            // 校验命令是否为子模块命令
            _actuator.Run(name, isRltToArg, &bIsOK, &bHasRun);
        }
        else
        {
            list_t<string>::iterator itr;
            CommandActuator subActuator;
            LOGGER(_log << "OnCommand:<" << _strput(name) << ">\n");
            for(itr = _module.begin(); itr != _module.end(); ++itr)
            {
                LOGGER(_log << "Module:<" << (*itr) << ">\n");
                subActuator = _runner->Actuator(*itr);
                // Set为了保存原来的参数
                _actuator.Set(subActuator).Run(name, isRltToArg, &bIsOK, &bHasRun);
            }
            _actuator.Set(_runner);
        }
        if(pIsOK != NULL)
        {
            (*pIsOK) = bIsOK;
        }
        if(pHasRun != NULL)
        {
            (*pHasRun) = bHasRun;
        }
        if(!bHasRun)
        {
            CommandActuator actuator(*_runner);
            string msg = _strput(name);
            msg += "命令冲突或不存在";
            actuator.Arg("CODE", DeviceError::ArgFormatErr)
                .Arg("MSG", msg).Run("SetLastError");
        }
        LOGGER(else
        {
            _log.WriteLine("/=------------");
            _log << "Result:[" << _actuator.Result().Count() << "]\n";
            enumer = _actuator.Result().GetEnumerator();
            while(enumer.MoveNext())
            {
                width = _max(enumer.Current().Key.length(), width);
                _log << _left_width(enumer.Current().Key, width) << " : <" << enumer.Current().Value << ">\n";
            }
        });
        return (*this);
    }
    /**
     * @brief 调用命令(用于触发连续调用的命令)
     * @date 2017-01-19 14:13
     * 
     * @param [in] name 需要调用的命令名称
     * @param [in,out] pIsOK [default:NULL] 命令运行结果
     * @param 运行结果依赖于上一次的结果,如果为false则停止运行该命令
     *
     * @param [out] pHasRun [default:NULL] 命令是否成功运行(有可能有命令不存在未运行)
     */
    CommandRunnerActuator& Call(const char* name, bool* pIsOK = NULL, bool* pHasRun = NULL)
    {
        bool isOK = (pIsOK != NULL) ? (*pIsOK) : true;
        if(!isOK)
        {
            return (*this);
        }
        return Run(name, false, pIsOK, pHasRun);
    }
    /// 输出结果
    inline CommandRunnerActuator& Result(ICommandHandler::Arguments& rlt)
    {
        StringArguments::CopyTo(_actuator.Result(), rlt);
        return (*this);
    }
    /// 输出结果
    inline CommandRunnerActuator& Result(IStringArgParser& parser, ByteBuilder& sRlt)
    {
        parser.ToString(_actuator.Result(), sRlt);
        return (*this);
    }
    /// 增加析构时的结束命令
    inline CommandRunnerActuator& Final(const char* name)
    {
        _disposeCmd = _strput(name);
        return (*this);
    }
    /// 执行析构命令
    bool OnFinal()
    {
        bool bRun = false;
        if(_disposeCmd.length() > 0)
        {
            Run(_disposeCmd.c_str(), false, NULL, &bRun);
            _disposeCmd = "";
        }
        return bRun;
    }
    /// 运行指定的命令
    inline bool OnCall(const char* name, bool* pIsRun = NULL)
    {
        bool bOK = false;
        Run(name, false, &bOK, pIsRun);
        return bOK;
    }
    /// 通过外部的参数运行命令
    inline bool OnCall(const char* name, IStringArguments& arg, IStringArguments& rlt, bool* pIsRun = NULL)
    {
        return _actuator.Run(name, arg, rlt, pIsRun);
    }
    /// 对Set的重载
    inline CommandRunnerActuator& operator[](const string& name)
    {
        return Set(name);
    }
    /// 反射接口
    template<class T>
    inline Ref<T> Reflect(const char* key)
    {
        return _actuator.Reflect<T>(key);
    }
};
//--------------------------------------------------------- 
/// 基于CommandRunner的命令编辑器
template<class TArgParser>
class CommandRunnerCmdEditor : public CommandCollection
{
protected:
    //----------------------------------------------------- 
    Ref<CommandRunner> _runner;
    /// 注册命令
    void _init()
    {
        _RegisteCMD(CommandRunnerCmdEditor, Registe);
        _RegisteCMD(CommandRunnerCmdEditor, Bind);
        _RegisteCMD(CommandRunnerCmdEditor, Rebind);
        _RegisteCMD(CommandRunnerCmdEditor, PrefixBind);
        _RegisteCMD(CommandRunnerCmdEditor, Unregiste);
    }
    //----------------------------------------------------- 
    bool _Bind(IStringArguments& arg, IStringArguments& rlt, bool isPrefixBind)
    {
        if(_runner.IsNull())
            return false;

        string sCmd;
        if(!arg.Get("CMD", sCmd) || sCmd.length() < 1)
            return false;

        string sBind;
        if(!arg.Get("Bind", sBind) || sBind.length() < 1)
            return false;

        string sItem;
        arg.Get("Item", sItem);

        // 如果没有该命令则新注册一个
        Ref<ComplexCommand> complexCmd = _runner->Registe(sCmd.c_str());
        if(arg["IsClear"].To<bool>(false))
        {
            complexCmd->Clear();
        }

        string sOption = arg["Option"].To<string>();
        ComplexCommand::CommandOption option = ComplexCommand::StringToOption(sOption.c_str());

        string sArg;
        bool isBind = arg.Get("Arguments", sArg);

        CommandSetter setter(*_runner);
        CommandSetter bindSetter(*_runner);
        if(sItem.length() > 0)
        {
            bindSetter = _runner->Get(sItem);
        }
        CommandSetter cmdSetter = setter.Cut(sCmd.c_str());
        CommandSetter subBindSetter = bindSetter.Cut(sBind.c_str());
        if(isBind)
        {
            TArgParser parser;
            StringArguments bindArg;
            parser.Parse(sArg.c_str(), bindArg);
            if(isPrefixBind)
            {
                cmdSetter.PrefixBind(subBindSetter, bindArg, option);
            }
            else
            {
                cmdSetter.Bind(subBindSetter, bindArg, option);
            }
        }
        else
        {
            if(isPrefixBind)
            {
                cmdSetter.PrefixBind(subBindSetter, option);
            }
            else
            {
                cmdSetter.Bind(subBindSetter, option);
            }
        }
        return true;
    }
    //----------------------------------------------------- 
public:
    //----------------------------------------------------- 
    /// 获取指定模块的脚本编辑器
    static Ref<CommandScriptActuator> NewScriptCMD(CommandRunner& runner, const char* devId, string* pFullName = NULL)
    {
        string scriptGrpName = "Script.";
        string scriptName;
        scriptName += devId;
        scriptName += ".Setter";

        Ref<CommandCollection> devCollection;
        Ref<CommandScriptActuator> devScript;
        string setterName;
        for(size_t i = 0;;++i)
        {
            setterName = scriptGrpName;
            setterName += scriptName;
            setterName += "[";
            setterName += ArgConvert::ToString(i);
            setterName += "]";

            devCollection = runner.Item(setterName);
            if(devCollection.IsNull())
            {
                if(pFullName != NULL)
                {
                    (*pFullName) = setterName;
                }
                runner.template New<CommandScriptActuator>(setterName.c_str(), &devScript);
                break;
            }
        }
        return devScript;
    }
    /// 重定向命令
    static size_t RebindCMD(CommandSetter& cmdEditor, Ref<CommandScriptActuator> script, 
        const char* devId, const char* spaceName, const char* cmds)
    {
        list_t<string> cmdlist;
        list_t<string>::iterator itr;
        StringHelper::Split(cmds, cmdlist, ';');

        bool isEmpty = _is_empty_or_null(spaceName);
        size_t count = 0;
        string cmdName;
        StringArguments arg;
        Ref<ComplexCommand> registeCmd = cmdEditor.LookUp("Registe");
        Ref<ComplexCommand> bindCmd = cmdEditor.LookUp("Bind");
        for(itr = cmdlist.begin();itr != cmdlist.end(); ++itr)
        {
            cmdName = "";
            if(!isEmpty)
            {
                cmdName += spaceName;
                cmdName += ".";
            }
            cmdName += (*itr);
            ++count;
            arg.Put("CMD", cmdName);
            arg.Put("IsClear", "true");
            arg.Put("Item", devId);
            arg.Put("Bind", *itr);
            script->Run(registeCmd, arg).Run(bindCmd, arg).Clear(true, true);
            arg.Clear();
        }
        return count;
    }
    /// 重定向单个命令
    static bool RebindCMD(CommandSetter& cmdEditor, Ref<CommandScriptActuator> script, const char* cmd, const char* subCmd)
    {
        StringArguments arg;
        Ref<ComplexCommand> registeCmd = cmdEditor.LookUp("Registe");
        Ref<ComplexCommand> bindCmd = cmdEditor.LookUp("Bind");

        ByteBuilder spaceName;
        ByteArray cmdName(subCmd);
        size_t index = StringConvert::IndexOf(cmdName, "::");
        if(index != SIZE_EOF)
        {
            spaceName = cmdName.SubArray(0, index);
            cmdName = cmdName.SubArray(index + 2);
        }
        if(cmdName.IsEmpty())
            return false;
        
        arg.Put("CMD", cmd);
        arg.Put("IsClear", "true");
        arg.Put("Item", spaceName.GetString());
        arg.Put("Bind", cmdName.GetString());
        script->Run(registeCmd, arg).Run(bindCmd, arg).Clear(true, true);
        arg.Clear();
        return true;
    }
    //----------------------------------------------------- 
    CommandRunnerCmdEditor() { _init(); }
    CommandRunnerCmdEditor(CommandRunner& runner)
    {
        _init();
        Set(runner);
    }
    CommandRunnerCmdEditor& Set(CommandRunner& runner)
    {
        _runner = runner;
        return (*this);
    }
    inline Ref<CommandRunner>& Runner()
    {
        return _runner;
    }
    /**
     * @brief 注册新的命令
     * @date 2017-01-12 22:00
     * 
     * @param [in] CMD : string 新的单个命令名称
     * @param [in] IsClear : bool [default:false] 如果命令存在,是否清空命令
     * 
     * @retval IsExist : bool 命令是否存在
     */
    LC_CMD_METHOD(Registe)
    {
        if(_runner.IsNull())
            return false;

        bool isExist = false;
        string cmd;
        if(!arg.Get("CMD", cmd) || cmd.length() < 1)
            return false;

        Ref<ComplexCommand> complexCmd = _runner->Registe(cmd.c_str(), &isExist);
        if(complexCmd.IsNull())
            return false;

        bool isClear = arg["IsClear"].To<bool>(false);
        if(isClear)
        {
            complexCmd->Clear();
        }

        rlt.Put("IsExist", ArgConvert::ToString<bool>(isExist));
        return true;
    }
    /**
     * @brief 重定向命令
     * @date 2017-12-02 09:37
     *
     * @param [in] CMD : string 需要重新绑定的多个命令名称,每个命令以;号分隔
     * @param [in] Item : string 需要操作的子模块
     * @param [in] Argument : string [default:""] 绑定的参数
     * @param [in] Option : uint [default:RunOnSuccess] 绑定的命令选项
     * @param [in] IsClear : bool [default:true] 是否清空已存在的命令
     * @param [in] SpaceName : string [default:""] 绑定后的命名空间名称
     */
    LC_CMD_METHOD(Rebind)
    {
        if(_runner.IsNull())
            return false;

        string sCmd;
        if(!arg.Get("CMD", sCmd) || sCmd.length() < 1)
            return false;
        string sItem;
        if(!arg.Get("Item", sItem) || sItem.length() < 1)
            return false;
        Ref<CommandCollection> refItem = _runner->Item(sItem);
        if(refItem.IsNull())
            return false;

        string spaceName = arg["SpaceName"].To<string>();
        if(spaceName.length() > 0)
            spaceName += ".";
        bool  isClear = arg["IsClear"].To<bool>(true);
        string sOption = arg["Option"].To<string>();
        ComplexCommand::CommandOption option = ComplexCommand::StringToOption(sOption.c_str());
        string sArg;
        bool isBind = arg.Get("Arguments", sArg);
        list_t<string> cmdlist;
        list_t<string>::iterator itr;
        StringHelper::Split(sCmd.c_str(), cmdlist, ';');
        if(cmdlist.size() < 1)
            return false;

        Ref<ComplexCommand> complexCmd;
        Ref<ComplexCommand> bindCmd;
        string cmdName;
        TArgParser parser;
        StringArguments bindArg;
        if(isBind)
        {
            parser.Parse(sArg.c_str(), bindArg);
        }

        for(itr = cmdlist.begin();itr != cmdlist.end(); ++itr)
        {
            cmdName = spaceName;
            cmdName += (*itr);

            complexCmd = _runner->Registe(cmdName.c_str());
            if(isClear)
            {
                complexCmd->Clear();
            }
            bindCmd = refItem->LookUp(itr->c_str());
            if(bindCmd.IsNull())
                continue;
            if(isBind)
            {
                complexCmd->Bind(bindCmd, bindArg, option);
            }
            else
            {
                complexCmd->Bind(bindCmd, option);
            }
        }
        return true;
    }
    /**
     * @brief 给指定的命令绑定命令
     * @date 2017-01-12 22:04
     * 
     * @param [in] CMD : string 需要绑定的单个命令
     * @param [in] Bind : string 被绑定的单个命令
     * @param [in] Item : string 被绑定的命令分组
     * @param [in] Option : string 绑定时的选项
     * @param [in] Arguments : string 绑定时的参数
     * @param [in] IsClear : bool [default:false] 是否清空原来的命令
     */
    LC_CMD_METHOD(Bind)
    {
        return _Bind(arg, rlt, false);
    }
    /**
     * @brief 前置绑定
     * @date 2017-01-12 22:13
     * 
     * @param [in] CMD : string 需要绑定的单个命令
     * @param [in] Bind : string 被绑定的单个命令
     * @param [in] Option : string 绑定时的选项
     * @param [in] Arguments : string 绑定时的参数
     */
    LC_CMD_METHOD(PrefixBind)
    {
        return _Bind(arg, rlt, true);
    }
    /**
     * @brief 删除指定名称的命令
     * @date 2017-01-12 21:46
     * 
     * @param [in] CMD : string 需要删除的命令名称
     * 
     * @retval CMD : string 找到并删除的命令名称
     */
    LC_CMD_METHOD(Unregiste)
    {
        if(_runner.IsNull())
            return false;

        list_t<string> cmdNames;
        arg.Get("CMD", cmdNames);

        list_t<string>::iterator itr;
        for(itr = cmdNames.begin();itr != cmdNames.end(); ++itr)
        {
            if(_runner->Unregiste(itr->c_str()))
            {
                rlt.Put("CMD", *itr);
            }
        }
        
        return true;
    }
    //----------------------------------------------------- 
};
//--------------------------------------------------------- 
} // nemespace driver
} // namespace application
} // namespace zhou_yb
//--------------------------------------------------------- 
#endif // _LIBZHOUYB_COMMANDRUNNER_H_
//========================================================= 